import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:hive_flutter/hive_flutter.dart';

class SplashPage extends StatefulWidget {
  const SplashPage({super.key});

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );

    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeIn),
    );

    _scaleAnimation = Tween<double>(begin: 0.8, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.elasticOut),
    );

    _animationController.forward();

    // 检查用户登录状态并跳转
    _checkUserStatus();
  }

  Future<void> _checkUserStatus() async {
    print('启动页开始执行');

    // 强制等待3秒，确保启动页显示
    await Future.delayed(const Duration(seconds: 3));

    if (!mounted) {
      print('组件已销毁，停止执行');
      return;
    }

    try {
      // 检查用户是否已登录
      final box = Hive.box('app');

      // 检查是否是首次使用
      final isFirstTime = box.get('isFirstTime', defaultValue: true);

      print('启动页调试信息:');
      print('isFirstTime: $isFirstTime');

      if (isFirstTime) {
        // 首次使用，标记为非首次，然后跳转到引导页
        await box.put('isFirstTime', false);
        print('首次使用，跳转到引导页');
        context.go('/onboarding');
        return;
      }

      // 通过是否存在有效 token 判断是否已登录
      final savedToken = box.get('accessToken');
      final bool isLoggedIn = savedToken is String && savedToken.isNotEmpty;
      final hasCompletedOnboarding = box.get(
        'hasCompletedOnboarding',
        defaultValue: false,
      );
      final hasCompletedProfileSetup = box.get(
        'hasCompletedProfileSetup',
        defaultValue: false,
      );

      print('isLoggedIn: $isLoggedIn');
      print('hasCompletedOnboarding: $hasCompletedOnboarding');
      print('hasCompletedProfileSetup: $hasCompletedProfileSetup');

      String targetRoute = '/login';

      if (isLoggedIn) {
        if (!hasCompletedOnboarding) {
          targetRoute = '/onboarding';
        } else if (!hasCompletedProfileSetup) {
          targetRoute = '/profile-setup';
        } else {
          targetRoute = '/dashboard';
        }
      }

      print('跳转到: $targetRoute');
      context.go(targetRoute);
    } catch (e) {
      print('启动页错误: $e');
      // 如果出现错误，默认跳转到引导页
      if (mounted) {
        context.go('/onboarding');
      }
    }
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).colorScheme.primary,
      body: Center(
        child: AnimatedBuilder(
          animation: _animationController,
          builder: (context, child) {
            return FadeTransition(
              opacity: _fadeAnimation,
              child: ScaleTransition(
                scale: _scaleAnimation,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 应用Logo
                    Container(
                      width: 100,
                      height: 100,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 16,
                            offset: const Offset(0, 8),
                          ),
                        ],
                      ),
                      child: Icon(
                        Icons.school,
                        size: 48,
                        color: Theme.of(context).colorScheme.primary,
                      ),
                    ),
                    const SizedBox(height: 20),
                    // 应用名称
                    Text(
                      'AI自习室',
                      style: TextStyle(
                        fontSize: 22,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                        letterSpacing: 1.2,
                      ),
                    ),
                    const SizedBox(height: 6),
                    Text(
                      '让学习更轻松',
                      style: TextStyle(
                        fontSize: 13,
                        color: Colors.white.withOpacity(0.8),
                        letterSpacing: 0.5,
                      ),
                    ),
                    const SizedBox(height: 48),
                    // 加载指示器
                    SizedBox(
                      width: 40,
                      height: 40,
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(
                          Colors.white.withOpacity(0.8),
                        ),
                        strokeWidth: 3,
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}
